<?php
declare (strict_types=1);

namespace app\common\model;

use addons\Target\facade\Target;

class Exchange extends Base
{
    protected function user(): object
    {
        return $this->hasOne(User::class, 'id', 'uid')
            ->field('id,code,nickname,mobile,photo');
    }

    protected function getAccountAttr($value): string
    {
        return get_pay_way($value);
    }

    protected function getTakeAccountAttr($value): string
    {
        return get_pay_way($value);
    }

    public static function add($param, $user, $system): array
    {
        parent::startTrans();
        try {
            if (!$system['exchange_open']) {
                throw new \Exception('转换功能已关闭');
            }
            if ($param['account'] == $param['take_account']) {
                throw new \Exception('转出转入不能为同一账户');
            }
            if ($system['exchange_min'] > $param['amount']) {
                throw new \Exception('最低转换金额：' . $system['exchange_min']);
            }
            if ($system['exchange_bs']) {
                if ($param['amount'] % $system['exchange_bs'] != 0) {
                    throw new \Exception('转换倍数：' . $system['exchange_bs']);
                }
            }
            if ($user->pay_password != md5($param['pay_password'])) {
                throw new \Exception('支付密码错误');
            }
            $account = $param['account'];
            if ($param['amount'] > $user->assets->$account) {
                throw new \Exception(get_pay_way($account) . '账户余额不足');
            }
            $cost = 0;
            if ($system['exchange_cost'] && $system['exchange_cost'] > 0) {
                $cost = round($param['amount'] * $system['exchange_cost'], 2);
            }
            $real_amount = round($param['amount'] - $cost, 2);
            parent::create([
                'uid' => $user->id,
                'account' => $param['account'],
                'take_account' => $param['take_account'],
                'amount' => $param['amount'],
                'cost' => $cost,
                'real_amount' => $real_amount,
                'status' => 2
            ]);
            Target::Account()->basics($user->id, $param['account'], $param['amount'], '转出', '-')
                ->createNormal();
            Target::Account()->basics($user->id, $param['take_account'], $real_amount, '转入', '+')
                ->createNormal();

            parent::commit();
        } catch (\Exception $e) {
            parent::rollback();

            return ['code' => -1, 'msg' => $e->getMessage()];
        }

        return ['code' => 1, 'msg' => '已转换'];
    }
}